//
//  KLMNetworking.swift
//  KLM
//
//  Created by 朱雨 on 2021/6/4.
//

import UIKit
import SwiftUI
import nRFMeshProvision

typealias KLMResponseSuccess = (_ response: AnyObject) -> Void
typealias KLMResponseFailure = (_ error: NSError) -> Void
typealias completionHandlerBlock = (_ responseObject: Data?, _ error: NSError?) -> Void

enum HTTPMethod: String {
    case post ///在请求体body中
    case get ///拼接到url上
    case delete ///拼接到url上
    case put
    case downLoad
    case image
}

class KLMNetworking: NSObject {
    
    private var networkingTool: AFHTTPSessionManager!
    
    static let ShareInstance = KLMNetworking()
    private override init() {
        super.init()
        networkingTool = AFHTTPSessionManager.init()
        let jsonType = "application/json"
        let textType = "text/html"
        let plainType = "text/plain"
        let set = NSSet.init(array: [jsonType,textType,plainType])
        networkingTool.responseSerializer.acceptableContentTypes = set as? Set<String>
    }
    
    private static var header: [String: String]? {
        ///["tenantCode": tenantCode]
        let versioncode = "iOS_\(KLM_APP_VERSION)"
        var head: [String: String] = ["tenantCode": tenantCode,
                                      "versioncode": versioncode
        ]
        if let token = KLMGetUserDefault("token") as? String {
            head["Authorization"] = token
        }
        return head
    }
    ///JSON类型数据
    static func jsonManagerWithHeader(head: [String: String]?) -> AFHTTPSessionManager{
        
        KLMNetworking.ShareInstance.networkingTool.responseSerializer = AFJSONResponseSerializer.init()
        KLMNetworking.ShareInstance.networkingTool.requestSerializer = AFJSONRequestSerializer.init()
        KLMNetworking.ShareInstance.networkingTool.requestSerializer.timeoutInterval = 15
        if let hee = head {
            for (key, value) in hee {
                KLMNetworking.ShareInstance.networkingTool.requestSerializer.setValue(value, forHTTPHeaderField: key)
            }
        }
        
        return KLMNetworking.ShareInstance.networkingTool
    }
    ///data类型数据
    private static func httpManagerWithHeader(head: [String: String]?) -> AFHTTPSessionManager{
        
        KLMNetworking.ShareInstance.networkingTool.responseSerializer = AFHTTPResponseSerializer.init()
        KLMNetworking.ShareInstance.networkingTool.requestSerializer = AFJSONRequestSerializer.init()
        KLMNetworking.ShareInstance.networkingTool.requestSerializer.timeoutInterval = 20
        if let hee = head {
            for (key, value) in hee {
                KLMNetworking.ShareInstance.networkingTool.requestSerializer.setValue(value, forHTTPHeaderField: key)
            }
        }

        return KLMNetworking.ShareInstance.networkingTool
    }
    ///传图片
    private static func imageManagerWithHeader(head: [String: String]?) -> AFHTTPSessionManager{
        
        KLMNetworking.ShareInstance.networkingTool.requestSerializer = AFHTTPRequestSerializer.init()
        KLMNetworking.ShareInstance.networkingTool.requestSerializer.timeoutInterval = 20
        KLMNetworking.ShareInstance.networkingTool.requestSerializer.setValue("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", forHTTPHeaderField: "Content-Type")
        if let hee = head {
            for (key, value) in hee {
                KLMNetworking.ShareInstance.networkingTool.requestSerializer.setValue(value, forHTTPHeaderField: key)
            }
        }

        return KLMNetworking.ShareInstance.networkingTool
    }
    
    ///请求方法分类
    private static func httpMethodSub(method: HTTPMethod? = .post, URLString: String,
                                      params: [String: Any]?, image: UIImage? = nil,
                           successBlock: @escaping (_ task: URLSessionDataTask, _ responseObject: Any?) -> Void,
                           failureBlock: @escaping (_ task: URLSessionDataTask?, _ error: Error) -> Void
    ) {
        
        switch method {
        case .post:
            self.jsonManagerWithHeader(head: header).post(URLString, parameters: params, progress: nil, success: successBlock, failure: failureBlock)
        case .get:
            self.jsonManagerWithHeader(head: header).get(URLString, parameters: params, progress: nil, success: successBlock, failure: failureBlock)
        case .put:
            self.jsonManagerWithHeader(head: header).put(URLString, parameters: params, success: successBlock, failure: failureBlock)
        case .delete:
            self.jsonManagerWithHeader(head: header).delete(URLString, parameters: params, success: successBlock, failure: failureBlock)
        case .downLoad:
            self.httpManagerWithHeader(head: header).get(URLString, parameters: params, progress: nil, success: successBlock, failure: failureBlock)
        case .image:
            self.imageManagerWithHeader(head: header).post(URLString, parameters: params, constructingBodyWith: { formData in
                if let image = image {
                    let data = image.compress(withMaxLength: 100*1024)
                    formData.appendPart(withFileData: data, name: "file", fileName: "deviceImage", mimeType: "image/png/jpg/jpeg")
                }
            }, progress: nil, success: successBlock, failure: failureBlock)
        default:
            break
        }
    }
    ///发送http请求
    static func httpMethod(method: HTTPMethod? = .post, URLString: String,
                           params: [String: Any]?, hudDismiss: Bool? = true, image: UIImage? = nil,
                     completion: @escaping completionHandlerBlock) {
        KLMLog("接口域名：\(URLString)\n请求参数：\(String(describing: params))")
        self.httpMethodSub(method: method, URLString: URLString, params: params, image: image) { task, responseObject in
            KLMLog("接口域名：\(URLString)\n请求返回数据: ")
            KLMLog(responseObject)
            
            if method == .downLoad {
                
                let data: NSData = responseObject as! NSData
                completion(data as Data, nil)
                return
            }
            
            do {
                ///json转data
                let data = try JSONSerialization.data(withJSONObject: responseObject as Any, options: [])
                ///data转model
                let model = try JSONDecoder().decode(KLMBaseModel.self, from: data)
                if model.code == 200 {
                    
                    completion(data, nil)
                    
                } else {
                    if hudDismiss == true {
                        SVProgressHUD.dismiss()
                    }
                    if model.code == 401 { //别人登录了
                        
                        ///清空数据
                        if KLMUserDefault.getValue(for: .token) != nil {
                            KLMHomeMesh.logout()
                            KLMLog("用户在其他地方登录")
                            UIViewController.switchLoginVc()
                        }
                        return
                    }
                    
                    var errorMsg = KLMLocalizable.LANGLOC("Unknow errors")
                    if let egMsg = model.egMsg {
                        errorMsg = egMsg
                    }
                    if Bundle.isChineseLanguage(), let msg = model.msg {
                        errorMsg = msg
                    } else if Bundle.isFrenchLanguage(), let frMsg = model.frMsg {
                        errorMsg = frMsg
                    } else if Bundle.isGermanLanguage(), let deMsg = model.deMsg {
                        errorMsg = deMsg
                    } else if Bundle.isDutchLanguage(), let nlMsg = model.nlMsg {
                        errorMsg = nlMsg
                    } else if Bundle.isNorskLanguage(), let noMsg = model.noMsg {
                        errorMsg = noMsg
                    } else if Bundle.isTurkishLanguage(), let trMsg = model.trMsg {
                        errorMsg = trMsg
                    } else if Bundle.isSpanishLanguage(), let esMsg = model.esMsg {
                        errorMsg = esMsg
                    } else if Bundle.isSwedishLanguage(), let seMsg = model.seMsg {
                        errorMsg = seMsg
                    } else if Bundle.isDanishLanguage(), let dkMsg = model.dkMsg {
                        errorMsg = dkMsg
                    } else if Bundle.isFinnishLanguage(), let fiMsg = model.fiMsg {
                        errorMsg = fiMsg
                    } else if Bundle.isJapaneseLanguage(), let jpMsg = model.jpMsg {
                        errorMsg = jpMsg
                    } else if Bundle.isKoreanLanguage(), let krMsg = model.krMsg {
                        errorMsg = krMsg
                    }
                    let resultDic = ["error": errorMsg]
                    let error = NSError.init(domain: "", code: model.code, userInfo: resultDic as [String : Any])
                    completion(nil, error)
                }
            } catch {
                if hudDismiss == true {
                    SVProgressHUD.dismiss()
                }
                let resultDic = ["error": error.localizedDescription]
                let error = NSError.init(domain: "", code: -1, userInfo: resultDic)
                completion(nil, error)
            }
            
        } failureBlock: { task, error in
            if hudDismiss == true {
                SVProgressHUD.dismiss()
            }
            KLMLog("接口域名：\(URLString)\n错误信息: ")
            KLMLog(error)
            let errors: NSError = error as NSError
            let resultDic = ["error": error.localizedDescription]
            if errors.code == -1011 {
                
                let errorData = errors.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as! Data
                do {
                    
                    let errorDic: [String: AnyObject] = try JSONSerialization.jsonObject(with: errorData, options: .mutableContainers) as! [String: AnyObject]
                    if let StateCode = errorDic["code"] as? Int {
                        
                        if StateCode == 400 { ///token过期，重新登录
                            ///清空数据
                            if KLMUserDefault.getValue(for: .token) != nil {
                                KLMHomeMesh.logout()
                                KLMLog("用户在其他地方登录")
                                UIViewController.switchLoginVc()
                            }
                            let retureError = NSError.init(domain: "", code: 401, userInfo: resultDic as [String : Any])
                            completion(nil, retureError)
                            return
                        }
                    }
                    
                } catch {
                    
                }
            }
            let retureError = NSError.init(domain: "", code: errors.code, userInfo: resultDic as [String : Any])
            completion(nil, retureError)
        }
    }
}

extension KLMNetworking {
    
    static func showCommonError() -> NSError {
        
        let resultDic = ["error": KLMLocalizable.LANGLOC("Data exception")]
        let error = NSError.init(domain: "", code: -1000, userInfo: resultDic as [String : Any])
        return error
    }
}

class KLMService: NSObject {
    //MARK: - 用户相关
    ///获取邮箱验证码 - 新接口
    static func getEmailCode(email: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        var language: Int = 0
        if Bundle.isChineseLanguage() {
            language = 1
        } else if Bundle.isFrenchLanguage() {
            language = 3
        } else if Bundle.isGermanLanguage() {
            language = 2
        } else if Bundle.isDutchLanguage() {
            language = 4
        } else if Bundle.isNorskLanguage() {
            language = 5
        } else if Bundle.isTurkishLanguage() {
            language = 6
        } else if Bundle.isSpanishLanguage() {
            language = 7
        } else if Bundle.isSwedishLanguage() {
            language = 8
        } else if Bundle.isDanishLanguage() {
            language = 9
        } else if Bundle.isFinnishLanguage() {
            language = 10
        } else if Bundle.isJapaneseLanguage() {
            language = 11
        } else if Bundle.isKoreanLanguage() {
            language = 12
        }
        let app: Int = 3
        let parame: [String : Any] = ["email": email,
                                      "language": language,
                                      "app": app]
   
        KLMNetworking.httpMethod(method: .get, URLString: KLMUrl("open/email/codeByAppAndLanguage"), params: parame) { responseObject, error in
            
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    ///获取手机验证码
    static func getPhoneCode(phone: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["phone": phone]
        KLMNetworking.httpMethod(method: .get, URLString: KLMUrl("open/sms/code"), params: parame) { responseObject, error in
            
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///登录
    static func login(username: String, password: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["username": username,
                      "password": password]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/auth/login"), params: parame) { responseObject, error in
            
            if error == nil {
                
                let model = try? JSONDecoder().decode(KLMUser.self, from: responseObject!)
                
                //登录成功，存储token
                KLMLog("登录成功：token = \(String(describing: model?.data.token))")
                KLMSetUserDefault("token", model?.data.token)
                
                ///存储个人账号密码
                KLMSetUserDefault("username", username)
                KLMSetUserDefault("password", password)
                
                ///存储个人信息
                KLMUser.cacheUserInfo(user: model?.data.userInfo)
                
                ///存储账号列表
                let account: KLMUserCache = KLMUserCache.init(account: username, password: password)
                KLMUser.saveAccount(account: account)
                
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///邮箱注册
    static func register(email: String, password: String, code: String, nickName: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["email": email,
                      "password": password,
                      "code": code,
                      "nickname": nickName]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/auth/register"), params: parame) { responseObject, error in
            
            if error == nil {
                
                ///存储个人账号密码
                KLMSetUserDefault("username", email)
                KLMSetUserDefault("password", password)
                
                NotificationCenter.default.post(name: .loginPageRefresh, object: nil)
                
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///手机号注册
    static func signUp(telephone: String, password: String, code: String, nickName: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["telephone": telephone,
                      "password": password,
                      "code": code,
                      "nickname": nickName]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/auth/register"), params: parame) { responseObject, error in
            
            if error == nil {
                
                ///存储个人账号密码
                KLMSetUserDefault("username", telephone)
                KLMSetUserDefault("password", password)
                
                NotificationCenter.default.post(name: .loginPageRefresh, object: nil)
                
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///修改密码
    static func updatePassword(oldPassword: String, newPassword: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let username = KLMGetUserDefault("username") as! String
        let parame = ["username": username,
                      "oldPassword": oldPassword,
                      "newPassword": newPassword]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/auth/update/password"), params: parame) { responseObject, error in
            
            if error == nil {
                
                KLMSetUserDefault("password", newPassword)
                
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///忘记邮箱密码
    static func forgetPassword(email: String, password: String, code: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["email": email,
                      "password": password,
                      "code": code]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/auth/forget/password"), params: parame) { responseObject, error in
            
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    ///忘记手机密码
    static func forgetMobilePassword(mobile: String, password: String, code: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["telephone": mobile,
                      "password": password,
                      "code": code]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/auth/forget/password"), params: parame) { responseObject, error in
            
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///退出登录
    static func logout(success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        KLMNetworking.httpMethod(URLString: KLMUrl("api/auth/logout"), params: nil) { responseObject, error in
            
            ///清空数据
            KLMMesh.logout()
            
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///用户注销
    static func deleteAccount(userid: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["id": userid]
        KLMNetworking.httpMethod(method: .delete, URLString: KLMUrl("api/user/delete"), params: parame) { responseObject, error in
            
            if error == nil {
                
                ///清空数据
                KLMMesh.logout()
                
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
        
    /// 给账号分配权限
    /// - Parameters:
    ///   - account: 账号
    ///   - type: unlock_duration为解锁功能，set_eyeprotection为护眼设置
    ///   - success: success
    ///   - failure: failure
    static func userAdvancedInvite(account: String, type: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["account": account,
                      "type": type
                    ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/user/user_advanced_invite"), params: parame) { responseObject, error in
            
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
//    app查询用户高级配置
    static func userAdvancedInfo(success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let params = [String: Int]()
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/user/user_advanced_info"), params: params) { responseObject, error in
            
            if error == nil {
                
                let model = try? JSONDecoder().decode(KLMAdvancedInfo.self, from: responseObject!)
                success(model?.data as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    ///更新用户个人信息
    static func updateUserInfo(nickname: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["nickname": nickname
                    ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/user/update_user_info"), params: parame) { responseObject, error in
            
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    //MARK: - Mesh相关
    static func addMesh(meshName: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let config = KLMMesh.createMesh(name: meshName)
        let parame = ["meshName": meshName,
                      "meshConfiguration": config
                    ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/mesh/id"), params: parame) { responseObject, error in
            
            if error == nil {
                let jsonObject: [String: AnyObject] = try! JSONSerialization.jsonObject(with: responseObject!, options: .mutableContainers) as! [String: AnyObject]
                let meshId: Int = jsonObject["data"] as! Int
                success(meshId as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    ///获取mesh列表
    static func getMeshList(success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        KLMNetworking.httpMethod(method: .get, URLString: KLMUrl("api/mesh/adminId/new"), params: nil) { responseObject, error in
            
            if error == nil {
                
                let model = try? JSONDecoder().decode(KLMHome.self, from: responseObject!)
                var homes: [KLMHomeModel]  = []
                if let model = model {
                    homes = model.data.admin + model.data.participant
                }
                success(homes as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    
    ///修改mesh信息
    static func editMesh(id: Int, meshName: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame: [String : Any] = ["id": id,
                                      "meshName": meshName]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/mesh/update_mesh"), params: parame) { responseObject, error in
            
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    /// 删除店铺
    /// - Parameters:
    ///   - id: 店铺ID
    ///   - success: success
    ///   - failure: failure
    static func deleteMesh(id: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        KLMNetworking.httpMethod(method: .delete, URLString: KLMUrl("api/mesh/\(id)"), params: nil) { responseObject, error in
            
            if error == nil {
                
                success(responseObject as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    ///查询店铺信息
    static func getMeshInfo(id: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let parame = ["meshId": id]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/mesh/query_mesh"), params: parame) { responseObject, error in
            
            if error == nil {
                
                let model = try? JSONDecoder().decode(KLMMeshInfo.self, from: responseObject!)
                let meshInfo = model?.data
                success(meshInfo as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    
    static func getMeshUsers(meshId: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["meshId": meshId]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/mesh/query_mesh_user_list"), params: parame) { responseObject, error in
            
            if error == nil {
                
                let model = try? JSONDecoder().decode(KLMMeshUserList.self, from: responseObject!)
                success(model as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    ///转移管理员
    static func transferAdmin(meshId: Int, fromId: Int, to id: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame: [String : Any] = ["meshId": meshId,
                      "userId": fromId,
                      "id": id]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/mesh/transfer_mesh_ownership"), params: parame) { responseObject, error in
            
            if error == nil {
                
                success(responseObject as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    
    static func getInvitationCode(meshId: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["meshId": meshId]
        KLMNetworking.httpMethod(method: .get, URLString: KLMUrl("api/mesh/invitationCode"), params: parame) { responseObject, error in
            
            if error == nil {
                
                let model = try? JSONDecoder().decode(KLMInvitationCode.self, from: responseObject!)
                let code = model?.data.result
                success(code as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    
    static func joinToHome(invitationCode: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["invitationCode": invitationCode]
        KLMNetworking.httpMethod(method: .get, URLString: KLMUrl("api/mesh/json"), params: parame) { responseObject, error in
            
            if error == nil {
                
                success(responseObject as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    ///删除mesh成员
    static func deleteUser(meshId: Int, userId: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["meshId": meshId,
                      "userId": userId]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/mesh/delete_mesh_user"), params: parame) { responseObject, error in
            
            if error == nil {
                
                success(responseObject as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    ///提降店铺中用户权限
    static func promoteDemoteUser(meshId: Int, userId: Int, promote: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["meshId": meshId,
                      "userId": userId,
                      "promote": promote]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/mesh/promote_demote_mesh_user"), params: parame) { responseObject, error in
            
            if error == nil {
                
                success(responseObject as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    
    ///mesh成员退出
    static func signOutUser(meshId: Int, userId: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["meshId": meshId,
                      "userId": userId]
        KLMNetworking.httpMethod(method: .delete, URLString: KLMUrl("api/mesh/signOut"), params: parame) { responseObject, error in
            
            if error == nil {
                
                success(responseObject as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    ///获取地址
    static func getMeshProvisonerAddress(meshId: Int, uuid: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame: [String : Any] = ["meshId": meshId,
                                      "uuid": uuid
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/meshApp/message"), params: parame) { responseObject, error in
            
            if error == nil {
                
                let model = try? JSONDecoder().decode(ProvisionerAddress.self, from: responseObject!)
                let address = model?.data.address
                success(address as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    
    ///修改mesh成员信息
    static func editMeshUserInfo(meshId: Int, userId: Int, roleType: Int? = nil, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        var parame: [String : Any] = ["meshId": meshId,
                                      "userId": userId
        ]
        if let roleType = roleType {
            parame["roleType"] = roleType
        }
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/mesh/modify_mesh_users"), params: parame) { responseObject, error in
            
            if error == nil {
                
                success(responseObject as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    ///申请店铺管理权限
    static func applyMeshAdmin(meshId: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["meshId": meshId,
                      "adminLock": 2 //1普通未锁定，2管理权限锁定中
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/mesh/apply_mesh_admin"), params: parame) { responseObject, error in
            
            if error == nil {
                
                success(responseObject as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    /// 店铺管理员锁定或解锁管理权限
    /// - Parameters:
    ///   - meshId: meshId
    ///   - adminLock: 1普通未锁定，2管理权限锁定中
    ///   - success: success
    ///   - failure: failure
    static func lockUnlockMeshAdmin(meshId: Int, adminLock: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["meshId": meshId,
                      "adminLock": adminLock
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/mesh/lockunlock_mesh_admin"), params: parame) { responseObject, error in
            
            if error == nil {
                
                success(responseObject as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    ///查询mesh下某个用户的信息
    static func selectMeshUserInfo(meshId: Int, userId: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["meshId": meshId,
                      "userId": userId
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/mesh/query_mesh_user_info"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(KLMMeshUser.self, from: responseObject!)
                success(model?.data as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    
    //MARK: - APP和固件版本
    ///查询APP版本
    static func checkAPPVersion(success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let scope = 0
        KLMNetworking.httpMethod(method: .get, URLString: KLMUrl("api/file/latestVersion/ios/\(scope)"), params: nil) { responseObject, error in
            
            if error == nil {
                
                let model = try? JSONDecoder().decode(KLMVersion.self, from: responseObject!)
                let data = model?.data
                success(data as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    
    ///查询服务器上最新的固件
    static func checkDFUVersion(deviceType: nodeDeviceType, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let type = "bluetooth"
        var index: Int = 0
        switch deviceType {
        case .meta1OneCamera:
            index = 1
        case .meta1NoCamera:
            index = 2
        case .qieXiang,
                .RGBControl,
                .danse,
                .shuangse,
                .Dali:
            index = 3
        case .meta2OneCamera,
                .meta2FreshOne:
            index = 4
        case .meta2NoCamera,
                .meta2FreshNo:
            index = 5
        case .meta2TwoCamera,
                .meta2FreshTwo:
            index = 6
        case .meta2NoCameraC10,
                .meta2FreshC10:
            index = 7
        case .gateway:
            index = 8
        case .scene1,
                .scene2,
                .scene3:
            index = 9
        case .singleFire1,
                .singleFire2,
                .singleFire3:
            index = 10
        case .metaG2NoCamera:
            index = 12
        case .metaG2OneCamera:
            index = 13
        case .metaG2TwoCamera:
            index = 14
        case .metaUniNo:
            index = 16
        case .metaUniOne:
            index = 17
        case .metaUniTwo:
            index = 18
        case .lunaWRGB:
            index = 19
        case .lunaWWCW:
            index = 20
        case .auraUniNoCamera:
            index = 21
        case .lukaNoCamera:
            index = 22
        case .auraUniOneCamera:
            index = 23
        case .lukaOneCamera:
            index = 24
        case .lukaUniOneCamera:
            index = 25
        case .MusesOneCamera:
            index = 26
        case .MusesTwoCamera:
            index = 27
        case .WWCW:
            index = 28
        case .kanoOneCamera:
            index = 29
        case .kanoTwoCamera:
            index = 30
        case .Accelerometer:
            index = 31
        case .wallLamp:
            index = 32
        case .kanoUniOneCamera:
            index = 33
        case .kanoUniTwoCamera:
            index = 34
        case .lunaWW:
            index = 35
        default:
            break
        }
        
        if index == 0 {
            return
        }
        
        KLMNetworking.httpMethod(method: .get, URLString: KLMUrl("api/file/latestVersion/\(type)/\(index)"), params: nil) { responseObject, error in
            
            if error == nil {
                
                let model = try? JSONDecoder().decode(KLMVersion.self, from: responseObject!)
                let data = model?.data
                success(data as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
            
    static func downLoadFile(id: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
                
        KLMNetworking.httpMethod(method: .downLoad, URLString: KLMUrl("api/file/download/\(id)"), params: nil) { responseObject, error in

            if error == nil {

                success(responseObject as AnyObject)

            } else {
                failure(error!)
            }
        }
    }
    ///查询appstore版本
    static func checkAppleStoreAppVersion(success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {

        //查询版本
        let url = "https://itunes.apple.com/lookup?id=\(AppleStoreID)"
        KLMLog("url = \(url)")
        KLMNetworking.jsonManagerWithHeader(head: nil).post(url, parameters: nil, progress: nil) { task, responseObject in

            KLMLog("查询成功:\(String(describing: responseObject))")
            guard let dic: [String: AnyObject] = responseObject as? [String : AnyObject], dic["resultCount"] as? Int == 1 else {
                SVProgressHUD.dismiss()
                success("" as AnyObject)
                return
            }

            guard let results: [AnyObject] = dic["results"] as? [AnyObject], let resultFirst: [String : AnyObject] = results.first as? [String : AnyObject], let newVersion = resultFirst["version"] else {
                SVProgressHUD.dismiss()
                success("" as AnyObject)
                return
            }
        
            KLMLog("newVersion = \(newVersion)")
            success(newVersion)

        } failure: { task, error in

            KLMLog("查询失败:\(error)")
            let resultDic = ["error": error.localizedDescription]
            let error = NSError.init(domain: "", code: -1, userInfo: resultDic as [String : Any])
            failure(error)
        }
    }
    //MARK: - 分组接口
    ///新增分组
    static func addGroup(meshId: Int, groupName: String, groupType: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let groupData: GroupData = GroupData()
        let data = try! JSONEncoder().encode(groupData)
        let groupDataStr = String(data: data, encoding: .utf8)
        
        let parame: [String : Any] = ["meshId": meshId,
                                      "groupName": groupName,
                                      "groupData": groupDataStr as Any,
                                      "groupType": groupType
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/group/create_group"), params: parame) { responseObject, error in
            
            if error == nil {
                
                success(responseObject as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    ///删除分组
    static func deleteGroup(groupId: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let mesh = KLMMesh.loadHome()!
        let parame = ["meshId": mesh.id,
                      "groupId": groupId]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/group/delete_group"), params: parame) { responseObject, error in
            //没有记录也是成功
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///查询群组信息
    static func selectGroup(groupId: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let mesh = KLMMesh.loadHome()!
        let parame = ["meshId": mesh.id,
                      "groupId": groupId]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/app/group/selectByMeshIdAndGroupId"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(KLMGroupModel.self, from: responseObject!)
//                let groupData = KLMTool.jsonToModel(model?.data.groupData, GroupData.self)
                ///这个方法，假如字符串没有key，模型有，模型key不是可选，就转化不出来。可选后可以转化但是key的值为nil,不会有默认值。
//                let groupData = KLMTool.getModelFromString(GroupData.self, from: model?.data.groupData)
                success(model?.data as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    ///修改分组
    static func updateGroup(groupId: Int, groupName: String? = nil, groupData: GroupData? = nil, sceneEnable: Int? = nil, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {

        let mesh = KLMMesh.loadHome()!
        var parame: [String : Any] = ["meshId": mesh.id,
                                      "groupId": groupId
        ]
        if let groupName = groupName {
            parame["groupName"] = groupName
        }
        if let groupData = groupData {
            let data = try! JSONEncoder().encode(groupData)
            let groupDataStr = String(data: data, encoding: .utf8)
            parame["groupData"] = groupDataStr
        }
        if let sceneEnable = sceneEnable {
            parame["sceneEnable"] = sceneEnable
        }
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/group/update_group"), params: parame) { responseObject, error in

            if error == nil {

                success(responseObject as AnyObject)

            } else {
                failure(error!)
            }
        }
    }
    ///添加设备到分组
    static func addDeviceToGroup(groupId: Int, uuid: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let mesh = KLMMesh.loadHome()!
        let parame: [String : Any] = ["meshId": mesh.id,
                                      "uuid": uuid,
                                      "groupId": groupId,
                                      ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/group/add_group_device"), params: parame) { responseObject, error in

            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///分组中删除设备
    static func removeDeviceFromGroup(groupId: Int, uuid: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let mesh = KLMMesh.loadHome()!
        let parame: [String : Any] = ["meshId": mesh.id,
                                      "uuid": uuid,
                                      "groupId": groupId,
                                      ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/group/remove_group_device"), params: parame) { responseObject, error in

            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    ///分组客流数据
    static func selectGroupData(meshId: Int, groupId: Int, startDate: String, endDate: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["meshId": meshId,
                      "groupId": groupId,
                      "startDate": startDate,
                      "endDate": endDate] as [String : Any]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/devicedata/query_group_people_data"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(KLMCustomerModel.self, from: responseObject!)
                success(model as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    //MARK: - 设备接口
    ///申请设备可用单播地址
    static func applyUnicastAddress(success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let home = KLMMesh.loadHome()!
        let parame = [
            "meshId": home.id
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/device/apply_unicast_address"), params: parame) { responseObject, error in

            if error == nil {
                let model = try? JSONDecoder().decode(KLMDeviceAddressData.self, from: responseObject!)
                let unicastAddress = model?.data.unicastAddress
                success(unicastAddress as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///新增设备
    static func addDevice(deviceName: String, deviceType: String, uuid: String, unicastAddress: UInt16, node: Node, commoditySku: String? = nil, wifiStatus: Int? = nil, deviceKey: String? = nil, productKey: String? = nil, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let mesh = KLMMesh.loadHome()!
        let zone: NSTimeZone = NSTimeZone.system as NSTimeZone
        var parame: [String : Any] = ["meshId": mesh.id,
                                      "uuid": uuid,
                                      "deviceName": deviceName,
                                      "deviceType": deviceType,
                                      "timezone ": zone.name,
                                      "unicastAddress": unicastAddress]
        if apptype == .targetGN {
            parame["timezone"] = "Asia/Shanghai"
        }
        if let commoditySku = commoditySku, KLMTool.isEmptyString(string: commoditySku) != nil {
            parame["productSku"] = commoditySku
        }
        if let wifiStatus = wifiStatus {
            parame["wifiStatus"] = wifiStatus
        }
        if let deviceKey = deviceKey {
            parame["deviceKey"] = deviceKey
        }
        if let productKey = productKey {
            parame["productKey"] = productKey
        }
        ///增加node信息
        let encoder = JSONEncoder()
        encoder.dateEncodingStrategy = .iso8601
        let data = try! encoder.encode(node)
        let newStr = String(data: data, encoding: .utf8)
        parame["meshNode"] = newStr
        
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/device/create_device"), params: parame) { responseObject, error in

            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///删除设备
    static func deleteDevice(uuid: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame: [String : Any] = [
            "uuid": uuid
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/device/delete_device_by_uuid"), params: parame) { responseObject, error in

            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }

    ///修改设备
    static func updateDevice(uuid: String, deviceName: String? = nil, commoditySku: String? = nil, wifiStatus: Int? = nil, controlMode: Int? = nil, unicastAddress: UInt16? = nil, iconUrl: String? = nil, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        var parame: [String : Any] = [
            "uuid": uuid
        ]
        if let deviceName = deviceName {
            parame["deviceName"] = deviceName
        }
        if let commoditySku = commoditySku, KLMTool.isEmptyString(string: commoditySku) != nil {
            parame["productSku"] = commoditySku
        }
        if let wifiStatus = wifiStatus {
            parame["wifiStatus"] = wifiStatus
        }
        if let controlMode = controlMode {
            parame["controlMode"] = controlMode
        }
        if let unicastAddress = unicastAddress {
            parame["unicastAddress"] = unicastAddress
        }
        if let iconUrl = iconUrl {
            parame["iconUrl"] = iconUrl
        }
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/device/update_device"), params: parame) { responseObject, error in

            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    ///查询设备
    static func selectDevice(uuid: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = [
            "uuid": uuid
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/app/device/selectByUuid"), params: parame) { responseObject, error in

            if error == nil {
                let model = try? JSONDecoder().decode(KLMDeviceModel.self, from: responseObject!)
                let device = model?.data
                success(device as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    ///绑定设备和网关
    static func bindGateway(deviceUuid: String, dataRelayUuid: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = [
            "deviceUuid": deviceUuid,
            "dataRelayUuid": dataRelayUuid
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/device/bind_data_relay"), params: parame) { responseObject, error in

            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    ///解绑设备与网关
    static func unbindGateway(deviceUuid: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = [
            "deviceUuid": deviceUuid
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/device/unbind_data_relay"), params: parame) { responseObject, error in

            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    ///网关下设备列表
    static func getGatewayBindList(dataRelayUuid: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let parame = [
            "dataRelayUuid": dataRelayUuid
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/device/query_data_relay_device"), params: parame) { responseObject, error in
            
            if error == nil {
                
                let model = try? JSONDecoder().decode(KLMCustomerModel.self, from: responseObject!)
                success(model?.data as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
        
    ///店铺中未绑定网关设备
    static func getAllDeviceUnBindGateway(meshId: Int, deviceType: String? = nil, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        var parame: [String : Any] = [
            "meshId": meshId
        ]
        
        if let deviceType = deviceType {
            parame["deviceType"] = deviceType
        }
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/device/query_mesh_data_relay_unbind_device"), params: parame) { responseObject, error in
            
            if error == nil {
                
                let model = try? JSONDecoder().decode(KLMCustomerModel.self, from: responseObject!)
                success(model?.data as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    
    ///查询单设备升级进度
    static func getDeviceUpgradeProgress(uuid: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let mesh = KLMMesh.loadHome()!
        let parame: [String : Any] = [
            "meshId": mesh.id,
            "uuid": uuid
        ]

        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/app/device/status/query_firmware_progress"), params: parame, hudDismiss: false) { responseObject, error in
            
            if error == nil {
                
                let model = try? JSONDecoder().decode(KLMOTAProgress.self, from: responseObject!)
                success(model?.data as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    
    ///重置单设备固件升级状态
    static func resetFirmwareProgress(uuid: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let mesh = KLMMesh.loadHome()!
        let parame: [String : Any] = [
            "meshId": mesh.id,
            "uuid": uuid
        ]

        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/app/device/status/reset_firmware_progress"), params: parame, hudDismiss: false) { responseObject, error in
            
            if error == nil {
                
                success(responseObject as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    
    ///配置设备图片
    static func configDeviceImage(uuid: String, image: UIImage, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let parame = [
            "uuid": uuid
        ]
        
        KLMNetworking.httpMethod(method: .image, URLString: KLMUrl("api/v2/saas/app/configdata/update_image"), params: parame, image: image) { responseObject, error in
            
            if error == nil {
                
                let model = try? JSONDecoder().decode(DeviceImage.self, from: responseObject!)
                success(model?.data.result as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    ///查询设备图片
    static func queryDeviceImage(uuid: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        ///imageType=1 代表是查看传感器图像
        let parame = [
            "uuid": uuid,
            "imageType": 1
        ] as [String : Any]
        
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/configdata/query_image"), params: parame) { responseObject, error in
            
            if error == nil {
                
                let model = try? JSONDecoder().decode(DeviceImage.self, from: responseObject!)
                success(model?.data.result as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    
    ///删除设备的SKU
    static func deleteProductSKU(uuid: String, productSku: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let mesh = KLMMesh.loadHome()!
        let parame: [String : Any] = [
            "meshId": mesh.id,
            "uuid": uuid,
            "productSku": productSku
        ]
        
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/devicedata/delete_product_sku_info"), params: parame) { responseObject, error in
            
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    //MARK: - 客流统计
    /// 获取柱状图数据
    static func selectBarCustomerCounting(uuid: String, startDate: String, endDate: String, productSku: String?, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        var parame = [
            "uuid": uuid,
            "startDate": startDate,
            "endDate": endDate,
        ]
        
        if let productSku = productSku {
            parame["productSku"] = productSku
        }
        
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/devicedata/flow_bar_data_by_date_uuid_sku"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(KLMCustomerModel.self, from: responseObject!)
                success(model as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    /// 获取饼状图数据
    static func selectPieCustomerCounting(uuid: String, startDate: String, endDate: String, productSku: String?, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        var parame = [
            "uuid": uuid,
            "startDate": startDate,
            "endDate": endDate,
        ]
        
        if let productSku = productSku {
            parame["productSku"] = productSku
        }
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/devicedata/flow_pie_data_by_date_uuid_sku"), params: parame) { responseObject, error in

            if error == nil {
                let model = try? JSONDecoder().decode(KLMCustomerModel.self, from: responseObject!)
                success(model as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    /// 查询店铺客流数据
    static func selectStoreCustomerCounting(meshId: Int, startDate: String, endDate: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame: [String : Any] = [
            "meshId": meshId,
            "startDate": startDate,
            "endDate": endDate
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/devicedata/flow_data_by_mesh_id"), params: parame) { responseObject, error in
            
            if error == nil {                
                let model = try? JSONDecoder().decode(KLMCustomerModel.self, from: responseObject!)
                success(model as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    /// 查询单灯实时人数
    /// - Parameters:
    ///   - uuid: 灯uuid
    ///   - success: success
    ///   - failure: failure
    static func selectSingleCurrentCounting(uuid: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame: [String : Any] = [
                                      "uuid": uuid
                                      ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/app/device/status/selectStatusByUuid"), params: parame) { responseObject, error in

            if error == nil {
                let model = try? JSONDecoder().decode(KLMDeviceModel.self, from: responseObject!)
                success(model?.data as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    /// SKU 列表
    /// - Parameters:
    ///   - uuid: 灯uuid
    ///   - success: success
    ///   - failure: failure
    static func selectSKUList(uuid: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = [
            "uuid": uuid
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/devicedata/select_product_sku_list"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(KLMCustomerModel.self, from: responseObject!)
                success(model as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    /// 是否有权限查看店铺热度
    /// - Parameters:
    ///   - meshId: 店铺ID
    ///   - success: 1 有权限 0 无权限
    ///   - failure: failure
    static func reportPermission(meshId: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = [
            "meshId": meshId
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/mesh/reportmesh_permission_check"), params: parame) { responseObject, error in
            
            if error == nil {
                let jsonObject: [String: AnyObject] = try! JSONSerialization.jsonObject(with: responseObject!) as! [String : AnyObject]
                let permission: Int = jsonObject["data"] as! Int
                success(permission as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    // MARK: - 店铺热度
    
    /// 商品热度店铺列表
    /// - Parameters:
    ///   - success: success
    ///   - failure: failure
    static func getReportMeshList(success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = [String: Any]()
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/mesh/reportmesh_list"), params: parame) { responseObject, error in
            
            if error == nil {
                
                let model = try? JSONDecoder().decode(KLMReportMesh.self, from: responseObject!)
                success(model?.data as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    
    /// 加入商品热度店铺
    /// - Parameters:
    ///   - invitationCode: 邀请码
    ///   - success: success
    ///   - failure: failure
    static func joinToReportHome(invitationCode: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["invitationCode": invitationCode]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/mesh/reportmesh_join"), params: parame) { responseObject, error in
            
            if error == nil {
                
                success(responseObject as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    
    /// 获取商品热度邀请码
    /// - Parameters:
    ///   - meshId: 商店meshid
    ///   - success: success
    ///   - failure: failure
    static func getReportInvitationCode(meshId: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["meshId": meshId]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/mesh/reportmesh_invitation_code"), params: parame) { responseObject, error in
            
            if error == nil {
                
                let model = try? JSONDecoder().decode(KLMInvitationCode.self, from: responseObject!)
                let code = model?.data.result
                success(code as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    
    /// 获取商品热度用户列表
    /// - Parameters:
    ///   - meshId: 店铺ID
    ///   - success: success
    ///   - failure: failure
    static func getReportUsers(meshId: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["meshId": meshId]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/mesh/reportmesh_all_user"), params: parame) { responseObject, error in
            
            if error == nil {
                
                let model = try? JSONDecoder().decode(KLMMeshUserList.self, from: responseObject!)
                success(model as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    
    /// 删除商品热度成员
    /// - Parameters:
    ///   - meshId: 店铺ID
    ///   - userId: 成员ID
    ///   - success: success
    ///   - failure: failure
    static func deleteReportUser(meshId: Int, userId: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["meshId": meshId,
                      "userId": userId]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/mesh/reportmesh_delete"), params: parame) { responseObject, error in
            
            if error == nil {
                
                success(responseObject as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    
    /// 热销单品top10
    /// - Parameters:
    ///   - startDate: 开始时间
    ///   - endDate: 结束时间
    ///   - success: success
    ///   - failure: failure
    static func hotSellerTopTen(startDate: String, endDate: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = [
            "startDate": startDate,
            "endDate": endDate
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/report/product_top_ten"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(KLMCustomerModel.self, from: responseObject!)
                success(model as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    /// 平均热度top10
    /// - Parameters:
    ///   - startDate: 开始时间
    ///   - endDate: 结束时间
    ///   - success: success
    ///   - failure: failure
    static func averageTopTen(startDate: String, endDate: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = [
            "startDate": startDate,
            "endDate": endDate
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/report/mesh_average_top_ten"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(KLMCustomerModel.self, from: responseObject!)
                success(model as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    /// 通过邮箱或手机号邀请用户加入网格
    /// - Parameters:
    ///   - meshId: 店铺ID
    ///   - account: 邮箱或手机号
    ///   - success: success
    ///   - failure: failure
    static func inviteReportUser(meshId: Int, account: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = [
            "meshId": meshId,
            "account": account
        ] as [String : Any]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/mesh/reportmesh_invite_user"), params: parame) { responseObject, error in
            
            if error == nil {
                
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    //MARK: - 场景类
    /// 查询场景列表
    /// - Parameters:
    ///   - meshId: 商场ID
    ///   - success: success
    ///   - failure: failure
    static func selectSceneLists(success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        guard let mesh = KLMMesh.loadHome() else {
            let error = NSError.init()
            failure(error)
            return
        }
        let parame = [
            "meshId": mesh.id
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/scene/query_scene_list"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(KLMScene.self, from: responseObject!)
                success(model?.data as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    /// 新增场景
    /// - Parameters:
    ///   - sceneName: 场景名称
    ///   - sceneData: 数据
    ///   - success: success
    ///   - failure: failure
    static func addScene(sceneName: String, sceneData: [KLMSceneActionModel], gatewayUuid: String? = nil, sceneSchedule: [KLMSceneAutomationModel]? = nil, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let mesh = KLMMesh.loadHome()!
        var parame:[String : Any] = [
            "meshId": mesh.id,
            "sceneName": sceneName,
            "sceneData": sceneData.map({$0.toJSON()})
        ]
        if let gatewayUuid = gatewayUuid {
            parame["gatewayUuid"] = gatewayUuid
        }
        if let sceneSchedule = sceneSchedule {
            parame["sceneSchedule"] = sceneSchedule.map({$0.toJSON()})
        }
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/scene/create_scene"), params: parame) { responseObject, error in
            
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    /// 查询场景信息
    /// - Parameters:
    ///   - sceneId: 场景ID
    ///   - success: success
    ///   - failure: failure
    static func selectSceneInfo(sceneId: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let parame = [
            "sceneId": sceneId
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/scene/query_scene"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(KLMSceneInfo.self, from: responseObject!)
                success(model?.data as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    /// 删除场景
    /// - Parameters:
    ///   - sceneId: 场景ID
    ///   - success: success
    ///   - failure: failure
    static func deleteScene(sceneId: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let parame = [
            "sceneId": sceneId
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/scene/delete_scene"), params: parame) { responseObject, error in
            
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    
    /// 更新场景
    /// - Parameters:
    ///   - sceneId: 场景ID
    ///   - sceneName: 场景名称
    ///   - sceneData: 数据
    ///   - success: success
    ///   - failure: failure
    static func upDateScene(sceneId: Int, sceneName: String, sceneData: [KLMSceneActionModel], gatewayUuid: String? = nil, sceneSchedule: [KLMSceneAutomationModel]? = nil, sceneConfig: RKConfigModel? = nil, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        var parame:[String : Any] = [
            "sceneId": sceneId,
            "sceneName": sceneName,
            "sceneData": sceneData.map({$0.toJSON()})
        ]
        if let gatewayUuid = gatewayUuid {
            parame["gatewayUuid"] = gatewayUuid
        }
        if let sceneSchedule = sceneSchedule {
            parame["sceneSchedule"] = sceneSchedule.map({$0.toJSON()})
        }
        if let sceneConfig = sceneConfig {
            parame["sceneConfig"] = sceneConfig.toJSON()
        }
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/scene/update_scene"), params: parame) { responseObject, error in
            
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    /// 面板按键绑定/解绑场景
    /// - Parameters:
    ///   - panelUuid: 面板ID
    ///   - buttonId: 按键 1 2 3
    ///   - sceneId: 场景ID
    ///   - success: success
    ///   - failure: failure
    static func createUpdateButtonScene(panelUuid: String, buttonId: Int, sceneId: Int? = nil, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let mesh = KLMMesh.loadHome()!
        var parame:[String : Any] = [
            "meshId": mesh.id,
            "panelUuid": panelUuid,
            "buttonId": buttonId
        ]
        if let sceneId = sceneId {
            parame["sceneId"] = sceneId
        }
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/scene/create_update_button_scene"), params: parame) { responseObject, error in

            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    /// 查询面板按键的场景
    /// - Parameters:
    ///   - panelUuid: 面板ID
    ///   - buttonId: 按键 1 2 3
    ///   - success: success
    ///   - failure: failure
    static func selectButtonScene(panelUuid: String, buttonId: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let mesh = KLMMesh.loadHome()!
        let parame:[String : Any] = [
            "meshId": mesh.id,
            "panelUuid": panelUuid,
            "buttonId": buttonId
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/scene/query_button_scene"), params: parame) { responseObject, error in

            if error == nil {
                let model = try? JSONDecoder().decode(KLMSceneInfo.self, from: responseObject!)
                success(model?.data as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    //MARK: - 测试APP使用
    
    /// 查询标定参数
    /// - Parameters:
    ///   - batchNumber: 料号
    ///   - success: 是否准备好快速标定
    ///   - failure: failure
    static func selectBiaoding(batchNumber: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = [
            "batchNumber": batchNumber
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/device/query_config"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(BiaoDingModel.self, from: responseObject!)
                success(model?.data.reachStandard as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    //MARK: - 其他
    ///Ping服务器
    static func ping(success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let currentHome = KLMMesh.loadHome()!
        let parame = ["meshId": currentHome.id]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/mesh/mobile_heart"), params: parame) { responseObject, error in
            
            if error == nil {
                
                let model = try? JSONDecoder().decode(KLMMeshUser.self, from: responseObject!)
                success(model?.data as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    ///搜索
    static func addSearch(searchContent: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["searchContent": searchContent
                    ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/search"), params: parame) { responseObject, error in
            
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///获取历史记录
    static func getHistoryData(page: String, limit: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["page": page,
                      "limit": limit
                    ]
        KLMNetworking.httpMethod(method: .get, URLString: KLMUrl("api/search/page"), params: parame) { responseObject, error in
            
            if error == nil {
                 
                let model = try? JSONDecoder().decode(KLMHistory.self, from: responseObject!)
                
                success(model as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///清除历史记录
    static func clearAllHistory(success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        KLMNetworking.httpMethod(method: .delete, URLString: KLMUrl("api/search/clearAll"), params: nil) { responseObject, error in
            
            if error == nil {
                
                success(responseObject as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    ///反馈建议
    static func feedBack(contacts: String, content: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["email": contacts,
                      "content": content]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/feedBack"), params: parame) { responseObject, error in
            
            if error == nil {
                
                success(responseObject as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    
    //MARK: - RK平台
    ///RK - OTA
    static func upgradeRKDevice(productKey: String, deviceKey: String, destVersion: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["productKey": productKey,
                      "deviceKey": deviceKey,
                      "destVersion": destVersion]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/rkdevice/upgrade_rkdevice"), params: parame) { responseObject, error in
            
            if error == nil {
                success(responseObject as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    ///查看RK图像
    static func viewRKDeviceImage(productKey: String, deviceKey: String, viewType: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame: [String : Any] = ["productKey": productKey,
                      "deviceKey": deviceKey,
                      "viewType": viewType]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/rkdevice/view_image_apply"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(RKImage.self, from: responseObject!)
                success(model?.data.direction as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///查询RK下的场景列表
    static func selectRKSceneLists(uuid: String, roomCode: String? = nil, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let mesh = KLMMesh.loadHome()!
        var parame: [String: Any] = [
            "meshId": mesh.id,
            "uuid": uuid
        ]
        if let roomCode = roomCode {
            parame["roomCode"] = roomCode
        }
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/rkdevice/query_rkdevice_scene"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(KLMScene.self, from: responseObject!)
                success(model?.data as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///查询RK分组的场景列表
    static func selectRKGroupSceneLists(groupId: Int, roomCode: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let mesh = KLMMesh.loadHome()!
        let parame: [String: Any] = [
            "meshId": mesh.id,
            "groupId": groupId,
            "roomCode": roomCode
        ]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/app/group/query_group_scene"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(KLMScene.self, from: responseObject!)
                success(model?.data as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///标注图像
    static func markRK(productKey: String, deviceKey: String, viewType: Int, startPoint: [Int], endPoint: [Int], radian: String? = nil, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        var parame: [String : Any] = ["productKey": productKey,
                                      "deviceKey": deviceKey,
                                      "viewType": viewType,
                                      "startPoint":startPoint,
                                      "endPoint": endPoint]
        if let radian = radian {
            parame["radian"] = radian
        }
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/rkdevice/image_mark"), params: parame) { responseObject, error in
            
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    /// 获取RK柱状图数据
    static func selectRKBarCustomerCounting(uuid: String, startDate: String, endDate: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = [
            "uuid": uuid,
            "startDate": startDate,
            "endDate": endDate,
        ]
                
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/people/rk_device_bar_data_by_uuid_date"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(KLMCustomerModel.self, from: responseObject!)
                success(model as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    ///查询店铺热力底图
    static func queryHeatmap(meshId: Int, uuid: String? = nil, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let parame = ["meshId": meshId]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/heatmap/query_heatmap"), params: parame) { responseObject, error in
            
            if error == nil {
                
                let model = try? JSONDecoder().decode(Heatmap.self, from: responseObject!)
                let mapUrl = model?.data.mapUrl
                success(mapUrl as AnyObject)
                
            } else {
                failure(error!)
            }
        }
    }
    
    ///更新 - 热力图坐标
    static func updateHeatmap(meshId: Int, uuid: String, areaStartX: Int, areaStartY: Int, areaEndX: Int, areaEndY: Int, rotate: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let parame = ["meshId": meshId,
                      "uuid": uuid,
                      "areaEndX": areaEndX,
                      "areaEndY": areaEndY,
                      "areaStartX": areaStartX,
                      "areaStartY": areaStartY,
                      "rotate": rotate] as [String : Any]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/heatmap/update_heatmap"), params: parame) { responseObject, error in
            
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    ///远程执行场景
    ///controlType，0执行，1预览，2取消
    static func remoteControlScene(uuid: String? = nil, sceneId: Int, controlType: Int, groupControl: Int, groupId: Int? = nil, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let mesh = KLMMesh.loadHome()!
        var parame: [String : Any] = ["meshId": mesh.id,
                                      "sceneId": sceneId,
                                      "groupControl": groupControl,
                                      "controlType": controlType]
        if let uuid = uuid {
            parame["uuid"] = uuid
        }
        if let groupId = groupId {
            parame["groupId"] = groupId
        }
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/configdata/remote_control_scene"), params: parame) { responseObject, error in
            
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///通过RK配置设备
    static func rkConfigDevice(uuid: String, model: RKConfigModel, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        var parame: [String: Any] = ["uuid": uuid]
        parame.merge(model.toJSON()!) { current, _ in
            current
        }
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/configdata/config_device_profile"), params: parame) { responseObject, error in
            
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///通过RK查询设备
    static func rkSelectConfigDevice(uuid: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        
        let parame = ["uuid": uuid]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/configdata/query_device_profile"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(RKConfigModelData.self, from: responseObject!)
                success(model?.data as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///查询场景控制器场合列表
    /// groupControl 0单设备，1组
    static func selectRKRoomLists(groupControl: Int, uuid: String? = nil, deviceType: String? = nil, groupId: Int? = nil, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let mesh = KLMMesh.loadHome()!
        var parame: [String: Any] = [
            "groupControl": groupControl,
            "meshId": mesh.id
        ]
        if let uuid = uuid {
            parame["uuid"] = uuid
        }
        if let deviceType = deviceType {
            parame["deviceType"] = deviceType
        }
        if let groupId = groupId {
            parame["groupId"] = groupId
        }
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/scene/query_scene_room_list"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(KLMRKRoomListsData.self, from: responseObject!)
                success(model?.data as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///切换场景控制器当前场合
    ///  groupControl  0单设备，1组
    static func switchRKRoomDefault(groupControl: Int, roomCode: String, uuid: String? = nil, groupId: Int? = nil, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let mesh = KLMMesh.loadHome()!
        var parame: [String: Any] = [
            "meshId": mesh.id,
            "roomCode": roomCode,
            "groupControl": groupControl
        ]
        if let uuid = uuid {
            parame["uuid"] = uuid
        }
        if let groupId = groupId {
            parame["groupId"] = groupId
        }
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/scene/switch_scene_room"), params: parame) { responseObject, error in
            
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    //MARK: - 远程控制
    ///远程控制设备
    ///groupControl 0单设备控 1组控
    static func remoteControlDevice(groupControl: Int, unicastAddress: UInt16? = nil, groupId: UInt16? = nil, opCode: String, dpCode: String, cfgInfo: String? = nil, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let mesh = KLMMesh.loadHome()!
        var parame: [String: Any] = [
                      "opCode": opCode,
                      "dpCode": dpCode,
                      "meshId": mesh.id,
                      "groupControl": groupControl]
        if let cfgInfo = cfgInfo {
            parame["cfgInfo"] = cfgInfo
        }
        if let unicastAddress = unicastAddress {
            parame["unicastAddress"] = unicastAddress
        }
        if let groupId = groupId {
            parame["groupId"] = groupId
        }
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/configdata/gateway_remote_control_device"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(RemoteModel.self, from: responseObject!)
                success(model?.data as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    ///网关列表
    static func selectGatewayList(success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let mesh = KLMMesh.loadHome()!
        let parame = ["meshId": mesh.id]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/device/query_gateway_list"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(KLMCustomerModel.self, from: responseObject!)
                success(model?.data as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///远程控制场景
    static func remoteControlScene(sceneId: Int, controlType: Int, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let mesh = KLMMesh.loadHome()!
        var parame: [String: Any] = [
                      "sceneId": sceneId,
                      "controlType": controlType,
                      "meshId": mesh.id]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/configdata/gateway_remote_control_scene"), params: parame) { responseObject, error in
            
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///远程查询设备状态
    static func remoteSelectDevice(unicastAddress: UInt16, opCode: String, dpCode: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let mesh = KLMMesh.loadHome()!
        var parame: [String: Any] = [
                      "opCode": opCode,
                      "dpCode": dpCode,
                      "meshId": mesh.id,
                      "unicastAddress": unicastAddress]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/configdata/gateway_remote_query_device"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(RemoteModel.self, from: responseObject!)
                success(model?.data as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    
    ///跨店远程控制
    static func acrossStoreRemoteControl(controlContent: [remoteStoreControl], opCode: String, dpCode: String, cfgInfo: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let parame: [String: Any] = [
            "controlContent": controlContent.map({$0.toJSON()}),
                      "opCode": opCode,
                      "dpCode": dpCode,
                      "cfgInfo": cfgInfo]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/configdata/gateway_remote_control_chain_device"), params: parame) { responseObject, error in
            
            if error == nil {
                success(responseObject as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///跨店查询分组
    static func selectAcrossStoreGroupListsSuccess(success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let user = KLMUser.getUserInfo()!
        let parame = [
            "userId": user.id]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/mesh/query_chain_group_name_list"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(remoteGroupData.self, from: responseObject!)
                success(model?.data as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
    ///跨店通过分组查询店铺
    static func selectAcrossStoreListsFromGroup(storeGroupCode: String, success: @escaping KLMResponseSuccess, failure: @escaping KLMResponseFailure) {
        let user = KLMUser.getUserInfo()!
        let parame: [String: Any] = [
            "userId": user.id,
            "storeGroupCode": storeGroupCode]
        KLMNetworking.httpMethod(URLString: KLMUrl("api/v2/saas/app/mesh/query_chain_mesh_group_list"), params: parame) { responseObject, error in
            
            if error == nil {
                let model = try? JSONDecoder().decode(remoteStoreData.self, from: responseObject!)
                success(model?.data as AnyObject)
            } else {
                failure(error!)
            }
        }
    }
}


